# PowerShell script to install patch

param (
    [string]$FD_DIR
)

$CUR_DIR = Split-Path -Parent $MyInvocation.MyCommand.Path

Write-Output "Current Directory: $CUR_DIR"

if (-not $FD_DIR) {
    Write-Output "Please specify the FD directory"
    exit 1
}

function Unzip-File {
    param (
        [string]$zipFilePath,
        [string]$destinationPath
    )
    try {
        Expand-Archive -Path $zipFilePath -DestinationPath $destinationPath -Force
    } catch {
        Write-Error "Failed to unzip $zipFilePath to $destinationPath"
        exit 1
    }
}

# Unzip the repository
Unzip-File -zipFilePath "$CUR_DIR\com.anlogic.sdk.repository-1.0.0-SNAPSHOT.zip" -destinationPath "$CUR_DIR\plugins"

# Remove old plugins
Remove-Item -Path "$FD_DIR\eclipse\plugins\com.anlogic.sdk*" -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item -Path "$FD_DIR\eclipse\plugins\ilg.gnumcueclipse.managedbuild.cross*" -Force -Recurse -ErrorAction SilentlyContinue
Remove-Item -Path "$FD_DIR\eclipse\plugins\ilg.gnumcueclipse.debug.gdbjtag.openocd*" -Force -Recurse -ErrorAction SilentlyContinue

# Copy new plugins
Write-Output "Copying new plugins..."
Copy-Item -Path "$CUR_DIR\plugins\plugins\*" -Destination "$FD_DIR\eclipse\plugins\" -Recurse -Force

# Unzip OpenOCD
Unzip-File -zipFilePath "$CUR_DIR\openocd_win64.zip" -destinationPath "$CUR_DIR\openocd_win64"

# Remove old OpenOCD files
Remove-Item -Path "$FD_DIR\toolchain\openocd\fpsoc\*" -Force -Recurse -ErrorAction SilentlyContinue

# Copy OpenOCD files
Write-Output "Copying OpenOCD files..."
Copy-Item -Path "$CUR_DIR\openocd_win64\*" -Destination "$FD_DIR\toolchain\openocd\fpsoc\" -Recurse -Force


# Unzip asct
Unzip-File -zipFilePath "$CUR_DIR\asct.zip" -destinationPath "$CUR_DIR\asct"

# Copy asct files
Write-Output "Copying asct files..."
Copy-Item -Path "$CUR_DIR\asct\*" -Destination "$FD_DIR\tools\asct\" -Recurse -Force

Write-Output "Patch installation completed successfully."